package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.ICartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuPrice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements ICartService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RemoteProductService remoteProductService;


    /**
     * 需求：
     * 单品数量不能超过99
     * 不同商品数量不能超过50
     *
     * @param skuId  商品skuId
     * @param skuNum 购买商品数量（增量）
     */

    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        //1.准备Redis  Hash类型的key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCarKey(userId);

        //2.准备Redis  Hash类型的 hashKey
        String hashKey = skuId.toString();

        //3.准备CartInfo
        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);

        int threshold = 99; //单品数量限制

        if (hashOperations.hasKey(hashKey)) { //在 做修改

            CartInfo cartInfo = hashOperations.get(hashKey);
            int totalNum = cartInfo.getSkuNum() + skuNum;
            cartInfo.setSkuNum(totalNum > threshold ? threshold : totalNum);
            cartInfo.setUpdateTime(new Date());
            hashOperations.put(hashKey, cartInfo);

        } else { //不在 做添加

            Long size = hashOperations.size(); //不同商品数量 ，上限50
            if (size >= 50) {
                throw new ServiceException("商品数量不能超过50件");
            }

            CartInfo cartInfo = new CartInfo();
            cartInfo.setCreateTime(new Date());
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuNum(skuNum); //默认是1

            //远程调用商品微服务，根据skuId查询ProductSku对象
            R<ProductSku> productSkuR = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (productSkuR.getCode() == R.FAIL) {  //判断远程接口调用是否降级处理了
                throw new ServiceException(productSkuR.getMsg());
            }
            ProductSku productSku = productSkuR.getData();
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setThumbImg(productSku.getThumbImg());
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuPrice(productSku.getSalePrice());

            hashOperations.put(hashKey, cartInfo);

        }
    }


    @Override
    public List<CartInfo> cartList() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCarKey(userId);

        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfoList = hashOperations.values(); //从redis中获取的旧价格数据

        //更新商品实时价格（只需要更新JVM堆内存对象的商品最新价格，redis中数据不变）
        //批量获取商品最新价格
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            List<Long> skuIdList = cartInfoList.stream().map((cartInfo) -> cartInfo.getSkuId()).toList();
            R<List<SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
            if (R.FAIL == skuPriceListR.getCode()) {
                throw new ServiceException(skuPriceListR.getMsg());
            }
            List<SkuPrice> skuPriceList = skuPriceListR.getData(); //数据库最新价格

            //为了从集合skuPriceList中找数据方便，我们需要转map
            Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream()
                    .collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));


            for (CartInfo cartInfo : cartInfoList) {
                /*skuPriceList.stream().filter((skuPrice) ->{
                    return skuPrice.getSkuId().equals(cartInfo.getSkuId())
                }).findFirst().ifPresent((skuPrice) ->{
                    cartInfo.setSkuPrice(skuPrice.getSalePrice());
                });*/
                cartInfo.setSkuPrice(skuIdToSalePriceMap.get(cartInfo.getSkuId()));
            }
            return cartInfoList;
        }


        return new ArrayList<>();
    }


    @Override
    public void deleteCart(Long skuId) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCarKey(userId);

        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        if (hashOperations.hasKey(skuId.toString())) {
            hashOperations.delete(skuId.toString());
        }
    }


    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCarKey(userId);

        String hashKey = skuId.toString();

        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        if (hashOperations.hasKey(hashKey)) {
            CartInfo cartInfo = hashOperations.get(hashKey);
            cartInfo.setIsChecked(isChecked);
            hashOperations.put(hashKey, cartInfo);
        }
    }


    @Override
    public void allCheckCart(Integer isChecked) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCarKey(userId);

        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        if (hashOperations.size() > 0) {
            List<CartInfo> cartInfoList = hashOperations.values();
            for (CartInfo cartInfo : cartInfoList) {
                cartInfo.setIsChecked(isChecked);
                hashOperations.put(cartInfo.getSkuId().toString(), cartInfo);
            }
        }

    }


    @Override
    public void clearCart() {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCarKey(userId);

        if (redisTemplate.hasKey(cartKey)) {
            redisTemplate.delete(cartKey);

        }

    }

    /**
     * 辅助工具方法，返回购物车的key
     *
     * @return 购物车的key
     * @Param userId 用户id
     */
    private String getCarKey(Long userId) {
        return "user:cart:" + userId;
    }


    //=============================================


    @Override
    public List<CartInfo> getCartCheckedList(Long userId) {
        List<CartInfo> checkedCartList = new ArrayList<>();
        String cartKey = getCarKey(userId);
        List<CartInfo> values = redisTemplate.opsForHash().values(cartKey);
        if (!CollectionUtils.isEmpty(values)) {
            for (CartInfo cartInfo : values) {
                if (cartInfo.getIsChecked().intValue() == 1) {
                    checkedCartList.add(cartInfo);
                }
            }

        }
        return checkedCartList;
    }


    @Override
    public Boolean updateCartPrice(Long userId) {
        String cartKey = getCarKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> values = hashOperations.values();
        if (!CollectionUtils.isEmpty(values)) {
            //批量获取商品最新价格
            List<Long> skuIdlist = values.stream().map(CartInfo::getSkuId).toList();
            R<List<SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIdlist, SecurityConstants.INNER);
            if (R.FAIL == skuPriceListR.getCode()) {
                throw new ServiceException(skuPriceListR.getMsg());
            }
            List<SkuPrice> skuPriceList = skuPriceListR.getData();
            Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

            for (CartInfo cartInfo : values) {
                if (cartInfo.getIsChecked().intValue() == 1) {
                    cartInfo.setCartPrice(skuIdToSalePriceMap.get(cartInfo.getSkuId()));
                    cartInfo.setSkuPrice(skuIdToSalePriceMap.get(cartInfo.getSkuId()));
                    hashOperations.put(cartInfo.getSkuId().toString(), cartInfo);

                }
            }

        }
        return true;
    }


    @Override
    public Boolean deleteCartCheckedList(Long userId) {
        String cartKey = getCarKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> values = hashOperations.values();
        if (!CollectionUtils.isEmpty(values)) {
            for (CartInfo cartInfo : values) {
                if (cartInfo.getIsChecked().intValue() == 1) {
                    hashOperations.delete(cartInfo.getSkuId().toString());
                }
            }
        }
            return true;
        }
    }














